<?php
namespace App\Http\Controllers\Company;

use Illuminate\Http\Request;
use App\Models\TeachesCompanyPpt;
use App\Models\TeachesCompanyVideo;
use App\Models\TeachesCompanyOffice;
use App\Models\TeachesCompany;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\Tags;
use App\Models\TeachesCompanyTags;
use App\Models\Company;
use App\Models\SystemSetting;
/**
 *
 * @author Joker
 *        
 */
class TeachesController extends CompanyController
{
    
    public function index()
    {
        if(empty($this->userinfo->company_id))
            return redirect(url('/company/center/companyinfo-default'));
        $documents = TeachesCompany::where('company_id','=',$this->userinfo->company_id)->orderBy('created_at','desc')->paginate(10);
        return view('company.document')->with('documents',$documents);
    }
    
    public function create(Request $req)
    {
        if(empty($this->userinfo->company_id))
            return redirect(url('/company/center/companyinfo-default'));
        
        $type = $req->input('type','');
        $viewPath = '';
        switch ($type)
        {
            case 'step':
                $viewPath = 'company.step';
                break;
                default:
                    $viewPath = 'company.upload';
        }
        $array =array('dest_dir'=>'teaches','attachment'=>true,'_token'=>csrf_token());
        $options =  str_replace('"','\'',json_encode($array));
        $opts = base64_encode(serialize($array));
        return view($viewPath)
               ->with('options',$options)
               ->with('opts',$opts);
    }
    
    public function edit($id)
    {
        if(empty($this->userinfo->company_id))
            return redirect(url('/company/center/companyinfo-default'));
        
        $array =array('dest_dir'=>'teaches','attachment'=>true,'_token'=>csrf_token());
        $options =  str_replace('"','\'',json_encode($array));
        $opts = base64_encode(serialize($array));
        $result = TeachesCompany::with('attachment')->where(array('company_id'=>$this->userinfo->company_id,'id'=>$id))->first();
        if(empty($result)) abort(404);
        $newsTag = array();
        foreach ($result->tags as $tag)
        {
            $newsTag[] = Tags::where('tags_id','=',$tag->tags_id)->first()->tags_name;
        }
        switch ($result->teaches_type)
        {
            case '1':
                $documentid = $result->video->id;
                $documenttype = 'video';
                break;
            case '2':
                $documentid = $result->office->id;
                $documenttype = 'office';
                break;
            case '3':
                $documentid = $result->ppt->id;
                $documenttype = 'ppt';
                break;
            default:
                $documentid = 0;
                $documenttype = 'step';
                $result->description = unserialize($result->description);
                $result->content = unserialize($result->content);
                $result->notice = unserialize($result->notice);
                $result->tools = unserialize($result->tools);
                return view('company.step')
                        ->with('options',$options)
                        ->with('result',$result)
                        ->with('documenttype',$documenttype)
                        ->with('documentid',$documentid)
                        ->with('newstag',implode(",", $newsTag))
                        ->with('opts',$opts);
        }
        return view('company.upload')
                ->with('options',$options)
                ->with('result',$result)
                ->with('documenttype',$documenttype)
                ->with('documentid',$documentid)
                ->with('newstag',implode(",", $newsTag))
                ->with('opts',$opts);
    }
    public function show(){}
    
    public function store(Request $req)
    {
        $this->validate($req, [
            'name'          => 'required|max:255',
            'description'   => 'required|min:40',
            'thumb'         => 'required',
        ]);
        
        $data = $req->only('documentid','url','documenttype','name','description','descimg','content','tools','notice','author','from',
                    'thumb','tagsinput','price','teaches_id');
        if(empty($this->userinfo->company_id))
        {
            return $this->formatJson('error','企业不能为空！');
        }
        $company = Company::find($this->userinfo->company_id);
        if(empty($company))
            return $this->formatJson('error','企业不存在！');
        
        switch ($data['documenttype'])
        {
            case 'ppt':
                $teachesAttach = TeachesCompanyPpt::find($data['documentid']);
                $data['teaches_type'] = 3;
                $data['content']= 'PPT教程';
                $data['tools'] = 'PPT教程';
                break;
            case 'video':
                $teachesAttach = TeachesCompanyVideo::find($data['documentid']);
                $data['teaches_type'] = 1;
                $data['content']= '视频教程';
                $data['tools'] = '视频教程';
                break;
            case 'office':
                $teachesAttach =TeachesCompanyOffice::find($data['documentid']);
                $data['teaches_type'] = 2;
                $data['content']= 'OFFFICE文档教程';
                $data['tools'] = 'OFFFICE文档教程';
                break;
            default :
                $data['teaches_type'] = 0;
                $data['description'] = serialize(array('name'=>$data['description'],'img'=>strToArray($data['descimg'],",")));
                $data['tools'] = serialize($data['tools']);
                $data['content']= serialize(stepContent($data['content']));
                $data['notice'] = serialize($data['notice']);
        }
        $tagids = array();
        $tags = strToArray($data['tagsinput'], ",");
        $post = array_except($data, ['documentid', 'url', 'documenttype', 'teaches_id','tagsinput','descimg']);
        $post['user_id'] = $this->uid;
        $post['sort'] = 0;
        $sysword = SystemSetting::where('varname','=','sensitive_words')->first();
        $wordstr = unserialize($sysword['value']);
        $data['name']           = filter_words($data['name'], $wordstr);
        $data['description']    = filter_words($data['description'], $wordstr);
        $data['tools']          = filter_words($data['tools'], $wordstr);
        $data['content']        = filter_words($data['content'], $wordstr);
        $data['notice']         = filter_words($data['notice'], $wordstr);
        
        if(!empty($data['teaches_id']) && $data['teaches_id'] >0 )
        {
            $teaches = TeachesCompany::find($data['teaches_id']);
            foreach ($post as $key=>$value)
            {
                $teaches->$key = $value;
            }
            DB::beginTransaction();
            try{
                foreach ($tags as $tg){
                    if(!empty(trim($tg)))
                    {
                        $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                        $tagids[] = $tagsModel->tags_id;
                    }
                }
                $teaches->save();
                TeachesCompanyTags::where('teaches_id','=',$teaches->id)->delete();
                foreach ($tagids as $tgd){
                    TeachesCompanyTags::firstOrCreate(['tags_id'=>$tgd,'teaches_id'=>$teaches->id]);
                }
                if(!empty($teachesAttach))
                {
                    switch ($data['documenttype'])
                    {
                        case 'ppt':
                            if(count($teaches->ppt)>0)
                            {
                                $oldPptId = $teaches->ppt->id;
                                if($oldPptId != $teachesAttach->id)
                                {
                                    $teachesAttach->tcompany_id = $teaches->id;
                                    TeachesCompanyVideo::where('id','=',$oldPptId)->delete();
                                    $teachesAttach->save();
                                }
                            }
                            else 
                            {
                                $teachesAttach->tcompany_id = $teaches->id;
                                $teachesAttach->save();
                            }
                            break;
                        case 'video':
                            if(count($teaches->video)>0)
                            {
                                $oldVideoId = $teaches->video->id;
                                if($oldVideoId != $teachesAttach->id)
                                {
                                    $teachesAttach->tcompany_id = $teaches->id;
                                    TeachesCompanyVideo::where('id','=',$oldVideoId)->delete();
                                    $teachesAttach->save();
                                }
                            }
                            else
                            {
                                $teachesAttach->tcompany_id = $teaches->id;
                                $teachesAttach->save();
                            }
                            break;
                        case 'office':
                            if(count($teaches->office)>0)
                            {
                                $oldOfficeId = $teaches->office->id;
                                if($oldOfficeId != $teachesAttach->id)
                                {
                                    $teachesAttach->tcompany_id = $teaches->id;
                                    TeachesCompanyOffice::where("id",'=',$oldOfficeId)->delete();
                                    $teachesAttach->save();
                                }
                            }
                            else
                            {
                                    $teachesAttach->tcompany_id = $teaches->id;
                                    $teachesAttach->save();
                            }
                            break;
                    }
                }
                DB::commit();
            }catch (\PDOException $e){
                DB::rollback();
                Log::info(['企业内训保存失败'=>$e->getMessage()]);
                return $this->formatJson('falied','教程保存失败！');
            }
        }
        else 
        {
            DB::beginTransaction();
            try{
                foreach ($tags as $tg){
                    if(!empty(trim($tg)))
                    {
                        $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                        $tagids[] = $tagsModel->tags_id;
                    }
                }
                
                $post['company_id'] = $this->userinfo->company_id;
                $teaches = TeachesCompany::firstOrCreate($post);
                foreach ($tagids as $tgd){
                    TeachesCompanyTags::firstOrCreate(['tags_id'=>$tgd,'teaches_id'=>$teaches->id]);
                }
                if(!empty($teachesAttach))
                {
                    $teachesAttach->tcompany_id = $teaches->id;
                    $teachesAttach->save();
                }
                $company->incrementAdd('teaches_count',1);
                DB::commit();
            }catch (\PDOException $e){
                DB::rollback();
                Log::info(['企业内训保存失败'=>$e->getMessage()]);
                return $this->formatJson('falied','教程保存失败！');
            }
        }
        return $this->formatJson('success','教程上传成功！',$teaches,'/company/center/document');
       
    }
    
    public function destroy($id) 
    {
        if(empty($this->userinfo->company_id))
            return $this->formatJson('error','企业信息不可为空！');
        $company = Company::find($this->userinfo->company_id);
        if(empty($company))
            return $this->formatJson('error','企业信息不可为空！');
        $teaches = TeachesCompany::where(['company_id'=>$company->id,'id'=>$id])->first();
        if(empty($teaches))
            return $this->formatJson('error','资源不存在！');
        DB::beginTransaction();
        try {
            $teaches->delete();
            $company->decrementDel('teaches_count',1);
            DB::commit();
        }catch (\PDOException $e){
            DB::rollback();
            Log::info(['企业内训删除'=>$e->getMessage()]);
            return $this->formatJson('falied','教程保存失败！');
        }
        return $this->formatJson('success','教程删除成功！');
    }
}